# -*- coding: UTF-8 -*-
#使用 pip install pillow 安装模块
#@author verket
#@date 2018.12.12
#将Plist图集切成散图
from PIL import Image
import xml.sax
import os,sys

#-----------------------------------------------------------------------
#图片帧信息
#-----------------------------------------------------------------------
class FrameInfo:
    def __init__(self):
        self.mFrameFileName = ''
        self.mFrameX = 0
        self.mFrameY = 0
        self.mFrameWidth = 0
        self.mFrameHeight = 0
        self.mRotate = False

#-----------------------------------------------------------------------
#Plist信息
#-----------------------------------------------------------------------
class PlistInfo:
    def __init__(self):
        self.mTextureFileName = ''
        self.mTextureSize = {'width':0,'height':0}
        self.mTextureFrameList = []


#-----------------------------------------------------------------------
#xml内容解析器
#-----------------------------------------------------------------------
class PlistHandler( xml.sax.ContentHandler ):
    def __init__(self):
        self.mPlistInfo = PlistInfo()
        self.mFrameInfo = FrameInfo()
        #标签
        self.mStartTag = ''
        self.mEndTag = ''
        #内容
        self.mKey = ''


    # 元素开始事件处理
    def startElement(self, tag, attributes):
        self.mStartTag = tag
        self.mEndTag = ''
        

    # 元素结束事件处理
    def endElement(self, tag):
        self.mEndTag = tag
    # 内容事件处理
    def characters(self, content):
        if self.mStartTag == 'key' and self.mEndTag == '' and content == 'frame':
            self.mFrameInfo =FrameInfo()
            self.mFrameInfo.mFrameFileName = self.mKey
        if self.mStartTag == 'string' and self.mEndTag == '' and self.mKey == 'frame':
            szStr = content.replace('{','')
            szStr = szStr.replace('}','')
            sizeArr = szStr.split(',')
            self.mFrameInfo.mFrameX = float(sizeArr[0])
            self.mFrameInfo.mFrameY = float(sizeArr[1])
            self.mFrameInfo.mFrameWidth = float(sizeArr[2])
            self.mFrameInfo.mFrameHeight = float(sizeArr[3])
        if self.mStartTag == 'true' and self.mEndTag == 'true' and self.mKey == 'rotated' and content == '\n':
            tem = self.mFrameInfo.mFrameWidth
            self.mFrameInfo.mFrameWidth = self.mFrameInfo.mFrameHeight
            self.mFrameInfo.mFrameHeight = tem
            self.mFrameInfo.mRotate = True
        if self.mStartTag == 'string' and self.mEndTag == '' and self.mKey == 'sourceSize':
            self.mPlistInfo.mTextureFrameList.append(self.mFrameInfo)
        if self.mStartTag == 'integer' and self.mEndTag == '' and self.mKey == 'width':
            self.mPlistInfo.mTextureSize['width'] = int(content)
        if self.mStartTag == 'integer' and self.mEndTag == '' and self.mKey == 'height':
            self.mPlistInfo.mTextureSize['height'] = int(content)
        if self.mStartTag == 'string' and self.mEndTag == '' and self.mKey == 'textureFileName':
            self.mPlistInfo.mTextureFileName = content

        if self.mStartTag == 'key' and self.mEndTag == '':
            self.mKey = content
            
#-----------------------------------------------------------------------



if ( __name__ == "__main__"):
    argvArr = sys.argv
    #argvArr = ['PlistCutImage.py', 'item4_anims_i6p.plist', 'item4_anims_i6p']
    if len(argvArr) < 3:
        print('[src plist file path] [output dir]')
        exit(1)
    if os.path.exists(argvArr[1]) == False:
        print("can't found " + argvArr[1])
        exit(1)
    # 创建一个 XMLReader
    parser = xml.sax.make_parser()
    # turn off namepsaces
    parser.setFeature(xml.sax.handler.feature_namespaces, 0)
    
    # 重写 ContextHandler
    Handler = PlistHandler()
    parser.setContentHandler( Handler )
    parser.parse(argvArr[1])

    print(argvArr)
    print('--------------------------')
    #创建输出目录
    if os.path.exists(argvArr[2]) == False:
        os.makedirs(argvArr[2])

    im = Image.open(Handler.mPlistInfo.mTextureFileName)
    for frame in Handler.mPlistInfo.mTextureFrameList:
        rect = (frame.mFrameX,frame.mFrameY,frame.mFrameX + frame.mFrameWidth,frame.mFrameY + frame.mFrameHeight)
        print(rect)
        newIm = im.crop(rect)
        if frame.mRotate == True:
            newIm = newIm.transpose(Image.ROTATE_90)
        #     newIm = newIm.rotate(90)
        print(argvArr[2] + '/' + frame.mFrameFileName)
        newIm.save(argvArr[2] + '/' + frame.mFrameFileName,'png')
